/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.reserve;

import java.util.Collection;

class CommitOperator extends TwoPhaseOperator {

	CommitOperator(ReserveManager rsvMgr) {

		super(rsvMgr);

	}

	final void commit(ReserveId rsvId) throws ReserveException {

		logger.debug("Try commit : " + rsvId);

		checkCommitAbort(rsvId);

		ReserveOperation ope = getCurrentOperation();
		ReserveInfo target = ope.getTargetReserveInfo();

		if (target != null) {
			Collection<ReserveInfo> reallocated = ope.getReallocatedReserveInfos();
			if (reallocated != null) {
				for (ReserveInfo r : reallocated) {
					if (r != target) {
						r.commitModification();
						recorder.store(r);
					}
				}
			}

			target.commitModification();
			target.clearWaitCommit();
			switch (ope.getOperationType()) {
			case reserve:
			case modify:
			case cancel:
				recorder.store(target);	// set waitCommit flag as false
				break;
			case destroy:
				ReserveInfo info = table.get(target.getReserveId());
				if (info != null) {
					// still target remains in reserve table
					recorder.store(target);
				} else {
					// target really deleted, don't store it again
				}
				break;
			case remove:
				// target really deleted, don't store it again
				break;
			default:
				assert(false);
				break;
			}
		}

		done();
		logger.debug("committed");

	}

}
